<?php
namespace XWAM\Addon\PXCallSystem\Controller;
/**
 * 发起呼叫接口
 * 
 * @since 1.0 2015-1-26 by sutroon
 */
class ApiCallController extends \Think\Controller {

    /**
     * 发起呼叫(支持多个号码一起呼叫)
     * 方法名:call
     * 参数:string:tel=呼叫号码(多个号码之间以英文逗号[,]分隔), int:uid=用户编号, string:password=用户密码, int:tsid=外呼策略编号, string:key=密匙(20150126)
     * 返回:[string] SUCCESS=无错误, E_ARGS_MISS=传参错误, E_USER_NO_FOUND=用户不存在, E_BLANCE=账户余额不足, E_STRATEGY_NO_FOUND=外呼策略不存在, E_SYSTEM1,E_SYSTEM2,E_SYSTEM3=系统级错误
     * 示例：
     *      http://117.25.177.102:8899/xcall/index.php/ApiCall/call/tel/13950076987/uid/9/password/123456/tsid/9/key/20150126.html
     *      http://117.25.177.102:8899/xcall/index.php/ApiCall/call/tel/13950076987,18506950021/uid/9/password/123456/tsid/9/key/20150126.html
     * @since 2015-1-26 by sutroon
     */
    public function call() {
        $tel = I('tel');
        $siteID = I('uid');
        $tsid = I('tsid');
        $password = I('password');
        $key = I('key');
        // # 鉴权用户
        if (!$tel || !$siteID || !$password || !$key || !$tsid) {
            die('E_ARGS_MISS'); // 参数有误
        }

        $admins = S('admin_siteid_names');
        if (!$admins) {
            $admins = M('tuser_member')->where("userType='ADMIN'")->getField(array('siteID', "concat(userName,'[',siteID,']') as userName"));
            S('admin_id_names', $admins, array('expire' => 15));
        }
        if (!$admins || !array_key_exists($siteID, $admins)) {
            die('E_USER_NO_FOUND'); // 用户不存在
        }

        // # 检测余额
        if (!BaseController::check_user_blance_state($siteID)) {
            die('E_BLANCE'); // 账户余额不足
        }
        // # 检测策略
        $tsids = S('taskstrategys');
        if (!$tsids) {
            $tsids = M('tcti_task_strategy')->getField('id, siteID, trunkName, sayExtension, outEcEnable, callerNo', true);
            S('taskstrategys', $tsids, array('expire' => 15));
        }
        if (!$tsids || !array_key_exists($tsid, $tsids)) {
            die('E_STRATEGY_NO_FOUND'); // 外呼策略不存在
        }
        // 修正任务状态咬住的问题    
        $trunkName = $tsids[$tsid]['trunkName'];
        $sayExtension = $tsids[$tsid]['sayExtension'];
        $outEcEnable = $tsids[$tsid]['outEcEnable'];
        $callerNo=$tsids[$tsid]['callerNo'];
        $uniqid = date('YmdHis');
        // 过滤重复号码
        $arrTels=  array_unique(explode(',', $tel));
        $tel=implode(',',$arrTels);
        // 送到8866端口，带的参数包括：trunkName;strategyID;taskID;siteID;sayExtension;outEcEnable;soureceID;uniqid;caller;called
        $content = "$trunkName;$tsid;$uniqid;$siteID;$sayExtension;$outEcEnable;0;$uniqid;$callerNo;$tel";
        // die($content); // NCpolice3805319;9;20150202105321;9;0;0;0;20150202105321;3805319;13950076987
        $msg = sofunc_socket_send($content, '', 8866);
        echo 'ok' == $msg ? $uniqid : 'E_SYSTEM3';
        if (I('debug')) {
            echo $msg;
        }
    }

    /**
     * 获取呼叫状态(支持多个号码一起呼叫,注意返回值)
     * 方法名:get_state
     * 参数:string:tel=呼叫号码(多个号码之间以英文逗号[,]分隔), int:uid=用户编号, string:password=用户密码, int:tsid=外呼策略编号, int:task=任务编号, string:key=密匙(20150126)
     * 返回:[json|null] {"start":"2015-01-27 12:04:24","end":"2015-01-27 12:04:32","dtmf":""} 或 [{"phone":"13950076987","start":"2015-01-27 12:04:24","end":"2015-01-27 12:04:32","dtmf":""},{"phone":"13950197906","start":"2015-01-26 18:03:43","end":"2015-01-26 18:03:55","dtmf":"8"}] 或 null
     * 示例：
     *      http://117.25.177.102:8899/xcall/index.php/ApiCall/get_state/tel/13950076987/uid/9/password/123456/tsid/9/key/20150126/task/20150203151122.html
     *      http://117.25.177.102:8899/xcall/index.php/ApiCall/get_state/tel/13950076987,18506950021,13950197906/uid/9/password/123456/tsid/9/key/20150126/task/20150203151122.html
     * @since 2015-1-27 by sutroon
     */
    public function get_state() {
        $tel = I('tel');
        $siteID = I('uid');
        $tsid = I('tsid');
        $task=I('task');
        $password = I('password');
        $key = I('key');
        // # 鉴权用户
        if (!$tel || !$siteID || !$password || !$key || !$tsid || !$task) {
            die('E_ARGS_MISS'); // 参数有误
        }
        if (false === strpos($tel, ',')) {
            $data = M('cdr')->where("siteID='$siteID' and taskStrategyID=$tsid and dst='$tel' and taskID=$task")->field("dst as 'phone',xcallAnswer as 'start',end,ifnull(dtmf,'') as dtmf")->find();
        } else {
            $tel = str_replace(',', "','", $tel);
            $data = M('cdr')->where("siteID='$siteID' and taskStrategyID=$tsid and taskID=$task and dst in ('$tel')")->field("dst as 'phone',xcallAnswer as 'start',end,ifnull(dtmf,'') as dtmf")->select();
        }
        // var_export($data);
        return $this->ajaxReturn($data);
    }

    // 座席来电弹屏 2014-12-16 by sutroon
    // 返回格式：extension_screen_popup_jsonp({"extension":"333","lineNum":false})
    public function seat_screen_popup() {
        $extension = I('exten');
        if (!$extension) {
            die('');
        }
        $memcache = new \Memcache;
        $memcache->connect('localhost', 11211);
        $lineNum = $memcache->get($extension);
        $memcache->delete($extension);
        $memcache->close();
        $data = array('extension' => $extension, 'lineNum' => $lineNum);
        echo 'extension_screen_popup_jsonp(' . json_encode($data) . ')';
    }

    // 座席获取最近10条通话记录 2014-12-16 by sutroon
    public function seat_get_callrecord_list() {
        $extension = I('exten');
        if (!$extension) {
            die('');
        }
        $cdrlist = M('cdr')->field('callerNo as lineNum,xcallAnswer as createdTime')->where("extension='$extension' and direction=1")->order('id desc')->limit(10)->select();
        echo 'extension_callrecord_list_jsonp(' . json_encode($cdrlist) . ')';
    }

    // 呼叫号码 2014-12-5 by sutroon
    public function seat_dialout_save() {
        $phone = I('phone');
        if (!$phone) {
            $this->act_ajaxReturn(false, '呼叫号码无效');
        }
        if ($this->loginInfo['userType'] != 'SEAT') {
            $this->act_ajaxReturn(false, '不是有效座席');
        }
        $list = M()->query('select u.extensionNumber, u.teamNumber, u.ctiTrunk, u.ctiCallerNo, u.ctiRegMode, tk.context from tuser_member u left join tcti_trunk tk on u.ctiTrunk=tk.account where u.id=' . $this->loginInfo['id']);
        if (!$list) {
            $this->act_ajaxReturn(false, '座席数据无效!');
        }
        $context = $list[0]['context'];
        // $context = 'xcall';
        $result = $this->dialout_func($list[0]['extensionNumber'], $phone, $list[0]['ctiTrunk'], $context, $list[0]['ctiCallerNo']);
        $this->act_ajaxReturn(true === $result, true === $result ? '正在发起呼叫...' : $result);
    }

    /**
     * 发起呼叫
     * 成功则返回true,否则返回错误消息
     * @param $phoneNumber
     * @param $trunkName
     * @param $context
     * @param $callerNo
     * @return bool
     * @since 1.0 2014-12-5 by sutroon 重构
     */
    function dialout_func($extension, $phoneNumber, $trunkName, $context, $callerNo) {
        //set_time_limit(0);
        //ob_implicit_flush(false);

        /*
          $params = array(
          'Channel' => "SIP/$extension", // 如果是电话则 Local/015003069007@user
          'Application' => 'Dial',
          'Data' => "SIP/$trunkName/$phoneNumber",
          'Priority' => 1,
          'Timeout' => 45000, // 等待被叫应答振铃时间
          // 'CallerID'=>$callerNo, // 来电显示的号码
          // 'Exten'=>'', 调用的拨号方案，对方接听电话后我们在这里实现交互
          );
          $result = $astman->send_request('Originate', $params);
          return $result['Response'] == 'Success' ? true : $result['Message'];
         */
        $astman = create_asmanager();
        $params['Channel'] = "SIP/$extension";
        $params['Application'] = 'Dial';
        $params['Data'] = 'Local/' . $phoneNumber . '@xcall/n';
        $params['Priority'] = 1;
        $params['Timeout'] = 45000;
        $result = $astman->send_request("Originate", $params);
        return $result['Response'] == 'Success' ? true : $result['Message'];
    }

}
